package com.fingard.dsp.bank.directbank.weixin01.domain;

import com.fingard.dsp.bank.directbank.weixin01.domain.common.DomainConfig;
import com.fingard.dsp.bank.directbank.weixin01.domain.common.DomainConstants;
import com.fingard.dsp.bank.directbank.weixin01.domain.task.DomainDetectionTimer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Timer;

/**
 * 【定时探测主域名连通性策略】接口实现
 * @author liujinhui
 */
public class DomainDetection extends AbstractDomainService implements IDomainService {

    private static Logger logger = LoggerFactory.getLogger(DomainDetection.class);

    private static DomainDetection INSTANCE;
    
    // 定时器-探测主域名连通性开启状态
    private static boolean DOMAIN_PROBE_TIMER_STATUS;

    /**
     * 探测主域名连通性定时器相关
     */
    private static DomainDetectionTimer domainDetectionTask;
    private static Timer domainDetectionTimer;

    private DomainDetection() {
        super();
        start(this);
    }

    private DomainDetection(DomainConfig config) {
        super(config);
        start(this);
    }

    public static synchronized DomainDetection getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new DomainDetection();
        }
        return INSTANCE;
    }

    /**
     * 以单例模式实例化对象
     * @param config
     * @return
     */
    public static synchronized DomainDetection getInstance(DomainConfig conf) {
        if (INSTANCE == null) {
            INSTANCE = new DomainDetection(conf);
        }
        return INSTANCE;
    }

    /**
     * 启动探测主域名连通性定时器，实现主备域名实时切换
     */
    private static synchronized void start(DomainDetection domainDetection) {
        DOMAIN_PROBE_TIMER_STATUS = true;
        if (domainDetectionTask == null) {
            if (domainDetectionTimer == null) {
                domainDetectionTimer = new Timer();
            }
            domainDetectionTask = new DomainDetectionTimer(domainDetectionTimer, domainDetection);
            int frequency = getConfig().getDomainProbeFrequency();
            domainDetectionTimer.scheduleAtFixedRate(domainDetectionTask,
                    DomainConstants.TIMER_DELAY_TIME, frequency);
            logger.info("【统计主域名实际请求成功率策略】定时器启动成功");
        }
    }
    
    /**
     * 修改定时器开启状态
     * @param value
     */
    public void setTimerStatus(boolean value) {
        DOMAIN_PROBE_TIMER_STATUS = value;
    }
    
    /**
     * 获取定时器开启状态
     * @return
     */
    public boolean getTimerStatus() {
        return DOMAIN_PROBE_TIMER_STATUS;
    }
}
